package com.demo.statemachine.d21;

import com.demo.statemachine.d20.TestEvents;
import com.demo.statemachine.d20.TestListener;
import com.demo.statemachine.d20.TestStates;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.action.Action;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.StateMachineBuilder;

/**
 * @Description TODO
 * @ClassName TimerStateMachineBuilder
 * @Date 2021/12/24 17:20
 * @Author 王东平
 */
@Slf4j
@Configuration
@EnableStateMachine
public class TimerStateMachineBuilder {
    @Autowired
    private BeanFactory beanFactory;
    private final static String MACHINEID = "timerMachine";
    public StateMachine<String, String> build() throws Exception {
        StateMachineBuilder.Builder<String, String> builder = StateMachineBuilder.builder();
        builder.configureConfiguration().withConfiguration()
                .machineId(MACHINEID)
                .beanFactory(beanFactory)
                .listener(new TimerListener());

        builder.configureStates().withStates()
                .initial("S1")
                .state("S2")
                .state("S3");
                ;

        builder.configureTransitions()
                .withExternal()
                    .source("S1").target("S2").event("E1")
                .and()
                .withExternal()
                    .source("S1").target("S3").event("E2")
                .and()
                .withInternal()
                    .source("S2").action(timerAction()).timer(2000)
                .and()
                .withInternal()
                    .source("S3").action(timerAction()).timerOnce(2000)
                ;
        return builder.build();
    }

    @Bean
    public TimerAction timerAction() {
        return new TimerAction();
    }
}
@Slf4j
class TimerAction implements Action<String, String> {

    @Override
    public void execute(StateContext<String, String> context) {
        log.warn("====== do something in every 1 sec");
    }
}
